import { getUserProfile, getUserByIdDetail, login } from '@/api/user'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    delUserInfo(state) {
      state.userInfo = {}
    },
    delToken(state) {
      state.token = ''
      localStorage.removeItem('token')
    }
  },
  actions: {
    async getUserInfo(context) {
      const res = await getUserProfile()
      // console.log('用户信息', res)
      context.commit('updateUserInfo', res.data)
      const info = await getUserByIdDetail(res.data.userId)
      // console.log('用户头像', info)
      context.commit('updateUserInfo', { ...res.data, ...info.data })
    },
    logout(context) {
      context.commit('delUserInfo')
      context.commit('delToken')
    },
    async initToken(context, formData) {
      const res = await login(formData)
      console.log(res, 'res')
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updateToken', res.data)
    }
  }
}
